package com.ice.app.project.generator.utils;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.commons.lang3.StringUtils;

import com.ice.app.project.generator.vo.ColumnEntity;
import com.ice.app.project.generator.vo.TableEntity;
import com.iceframework.core.utils.FreemarkerUtils;

/**
 * 代码生成器 工具类
 * 
 * @author Palo
 *
 */
public class GeneratorUtils {

	private final static String TEMPLATE_BASE_PATH = System.getProperty("user.dir")+"\\src\\main\\resources\\";
	
	/**
	 * 多主键key路径
	 */
	private final static String TEMPLATE_PATH_ENTITY_IDS = "template/ids/entity.key.java.ftl";

	/**
	 * 单主键
	 * 
	 * @return
	 */
	public static List<String> getIdTemplates() {
		List<String> templates = new ArrayList<String>();
		templates.add("template/id/controller.java.ftl");
		templates.add("template/id/service.java.ftl");
		templates.add("template/id/mapper.java.ftl");
		templates.add("template/id/mapper.xml.ftl");
		templates.add("template/id/entity.java.ftl");
		templates.add("template/id/index.js.ftl");
		templates.add("template/id/index.html.ftl");
		templates.add("template/id/edit.html.ftl");
		templates.add("template/id/edit.js.ftl");
		return templates;
	}

	/**
	 * 多主键
	 * 
	 * @return
	 */
	public static List<String> getIdsTemplates() {
		List<String> templates = new ArrayList<String>();
		templates.add("template/ids/controller.java.ftl");
		templates.add("template/ids/service.java.ftl");
		templates.add("template/ids/mapper.java.ftl");
		templates.add("template/ids/mapper.xml.ftl");
		templates.add("template/ids/entity.java.ftl");
		templates.add(TEMPLATE_PATH_ENTITY_IDS);
		templates.add("template/id/index.js.ftl");
		templates.add("template/id/index.html.ftl");
		templates.add("template/id/edit.html.ftl");
		templates.add("template/id/adedit..ftl");
		return templates;
	}

	/**
	 * 无主键
	 * 
	 * @return
	 */
	public static List<String> getNothingTemplates() {
		List<String> templates = new ArrayList<String>();
		return templates;
	}

	/**
	 * 生成代码
	 * @throws Exception 
	 */
	public static void generatorCode(Map<String, String> table, List<Map<String, String>> columns,
			ZipOutputStream zip) throws Exception {
		// 配置信息
		Configuration config = getConfig();

		// 表信息
		TableEntity tableEntity = new TableEntity();
		tableEntity.setTableName(table.get("tableName"));
		tableEntity.setComments(table.get("tableComment"));
		// 表名转换成Java类名
		String className = tableToJava(tableEntity.getTableName(), config.getString("tablePrefix"));
		tableEntity.setClassName(className);
		tableEntity.setClassname(StringUtils.uncapitalize(className));

		// 列信息
		List<ColumnEntity> columsList = new ArrayList<>();
		List<ColumnEntity> pkList = new ArrayList<>();
		List<ColumnEntity> allColumsList = new ArrayList<>();
		
		//去重
		List<String> keys = new ArrayList<>();
		for (Map<String, String> column : columns) {
			ColumnEntity columnEntity = new ColumnEntity();
			columnEntity.setColumnName(column.get("columnName"));
			columnEntity.setDataType(column.get("dataType"));
			columnEntity.setComments(column.get("columnComment")==null?" ":column.get("columnComment"));
			columnEntity.setExtra(column.get("extra")==null?" ":column.get("extra"));

			// 列名转换成Java属性名
			String attrName = columnToJava(columnEntity.getColumnName());
			columnEntity.setAttrName(attrName);
			columnEntity.setAttrname(StringUtils.uncapitalize(attrName));

			// 列的数据类型，转换成Java类型
			String attrType = config.getString(columnEntity.getDataType().toLowerCase(), "unknowType");
			columnEntity.setAttrType(attrType);

			// 是否主键
			if ("PRI".equalsIgnoreCase(column.get("columnKey"))) {
				pkList.add(columnEntity);
			} else {
				columsList.add(columnEntity);
			}
			
			//记录重复
			if(!keys.contains(columnEntity.getAttrName())) {
				keys.add(columnEntity.getAttrName());
			}else {
				continue;
			}
			allColumsList.add(columnEntity);
		}
		
		tableEntity.setColumns(columsList);
		tableEntity.setPk(pkList);
		tableEntity.setAllColumns(allColumsList);

		// 封装模板数据
		Map<String, Object> map = new HashMap<>();
		// 表名
		map.put("tableName", tableEntity.getTableName());
		// 表备注
		map.put("comments", tableEntity.getComments()==null?" ":tableEntity.getComments());
		// 主键集合
		map.put("pk", tableEntity.getPk());
		map.put("pathName", tableEntity.getClassname().toLowerCase());
		// 所有列，不包含主键
		map.put("columns", tableEntity.getColumns());
		// 所有列，包含主键
		map.put("allColumns", tableEntity.getAllColumns());
		// 包名称
		map.put("package", config.getString("package"));
		// 作者
		map.put("author", config.getString("author")==null?" ":config.getString("author"));
		// Email
		map.put("email", config.getString("email")==null?" ":config.getString("email"));
		// 创建时间
		map.put("datetime", DateUtils.format(new Date(), "yyyy-MM-dd hh:mm:ss"));
		// 前端名称
		map.put("moduleName", config.getString("mainModule"));

		// 类名
		map.put("className", tableEntity.getClassName());
		// 对象名
		map.put("objName", tableEntity.getClassname());
		
		// 获取模板列表
		List<String> templates = null;
		if (tableEntity.getPk().size() == 0) {
			templates = getNothingTemplates();
		}
		if (tableEntity.getPk().size() == 1) {
			templates = getIdTemplates();
		}
		if (tableEntity.getPk().size() > 1) {
			templates = getIdsTemplates();
		}

		// 模板引擎初始化
		FreemarkerUtils freemarker  = new FreemarkerUtils(TEMPLATE_BASE_PATH);
		freemarker.init();
		for (String template : templates) {
			String temp = freemarker.processToString(template, map);
			StringWriter sw = new StringWriter();
			sw.append(temp);
			try {
				zip.putNextEntry(new ZipEntry(getFileName(template, tableEntity.getClassName(),
						config.getString("package"), toLowerCaseFirstOne(className))));
				IOUtils.write(sw.toString(), zip, "UTF-8");
				IOUtils.closeQuietly(sw);
				zip.closeEntry();
			} catch (IOException e) {
				throw new RuntimeException("渲染模板失败，表名：" + tableEntity.getTableName(), e);
			}
		}
	}

	/**
	 * 列名转换成Java属性名
	 */
	public static String columnToJava(String columnName) {
		return WordUtils.capitalizeFully(columnName, new char[] { '_' }).replace("_", "");
	}

	/**
	 * 表名转换成Java类名
	 */
	public static String tableToJava(String tableName, String tablePrefix) {
		String[] split = {tablePrefix};
		if (StringUtils.isNotBlank(tablePrefix)) {
			if(tablePrefix.contains(",")) {
				split = tablePrefix.split(",");
			}
			for (String str : split) {
				tableName = tableName.replaceFirst(str, "");
			}
		}
		return columnToJava(tableName);
	}

	/**
	 * 获取配置信息
	 */
	public static Configuration getConfig() {
		try {
			return new PropertiesConfiguration("generator.properties");
		} catch (ConfigurationException e) {
			throw new RuntimeException("获取配置文件失败，", e);
		}
	}

	/**
	 * 获取文件名
	 */
	public static String getFileName(String template, String className, String packageName, String moduleName) {
		String packagePath = "java" + File.separator;
		String frontPath = "webapp" + File.separator + "project" + File.separator;
		if (StringUtils.isNotBlank(packageName)) {
			packagePath += packageName.replace(".", File.separator) + File.separator;
		}
		if (template.contains("index.js.ftl")) {
			return frontPath + toLowerCaseFirstOne(className) + File.separator + toLowerCaseFirstOne(className) + "Index.js";
		}
		if (template.contains("index.html.ftl")) {
			return frontPath + toLowerCaseFirstOne(className) + File.separator + toLowerCaseFirstOne(className) + "Index.html";
		}
		if (template.contains("edit.html.ftl")) {
			return frontPath + toLowerCaseFirstOne(className) + File.separator + toLowerCaseFirstOne(className) + "Edit.html";
		}
		if (template.contains("edit.js.ftl")) {
			return frontPath + toLowerCaseFirstOne(className) + File.separator + toLowerCaseFirstOne(className) + "Edit.js";
		}
		if (template.contains("service.java.ftl")) {
			return packagePath + moduleName + File.separator + "service" + File.separator + className + "Service.java";
		}
		if (template.contains("mapper.java.ftl")) {
			return packagePath + "mapper" + File.separator + className + "Mapper.java";
		}
		if (template.contains("entity.java.ftl")) {
			return packagePath + "entity" + File.separator + className + ".java";
		}
		if (template.contains(TEMPLATE_PATH_ENTITY_IDS)) {
			return packagePath + "entity" + File.separator + className + "Key.java";
		}
		if (template.contains("controller.java.ftl")) {
			return packagePath + moduleName + File.separator + "controller" + File.separator + className + "Controller.java";
		}
		if (template.contains("mapper.xml.ftl")) {
			return packagePath + "mapper" + File.separator + className + "Mapper.xml";
		}
		return null;
	}

	// 首字母转小写
	public static String toLowerCaseFirstOne(String s) {
		if (Character.isLowerCase(s.charAt(0))) {
			return s;
		} else {
			return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
		}
	}

}